package com.rybbaby.tss.platform.codeGenerate.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.bean.CommonFormAttr;
import com.rybbaby.tss.core.bean.ForeignKeyBean;
import com.rybbaby.tss.core.bean.TableBean;
import com.rybbaby.tss.core.bean.TableColumnBean;
import com.rybbaby.tss.core.code.generate.config.GenerateConfig;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.platform.codeGenerate.service.ICodeGenerateService;
import com.rybbaby.tss.platform.sysTableColumn.entity.SysTableColumnMapping;
import com.rybbaby.tss.platform.sysTableColumn.service.ISysTableColumnMappingService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.*;
import java.util.function.Predicate;

/**
 * @description 模块业务代码生成
 * 
 * @author 谢进伟
 * 
 * @createDate 2016-1-31 下午6:57:32
 */
@Controller
@RequestMapping(value = "codeGenerateController")
public class CodeGenerateController extends BaseController {
	
	@Autowired
	private ICodeGenerateService codeGenerateService;
	@Autowired
	private ISysTableColumnMappingService sysTableColumnMappingService;
	
	@RequestLog(content = "进入设置代码生成参数第一步页面")
	@RequestMapping(value = "showFirstStepSettingPage")
	public ModelAndView showFirstStepSettingPage() {
		ModelAndView mav = new ModelAndView();
		GenerateConfig defaultConfig = new GenerateConfig();
		mav.setViewName(PropertiesReadUtil.getStringProperty("showFirstStepSettingPageView"));
		mav.addObject("defaultConfig" , defaultConfig);
		return mav;
	}
	
	@RequestLog(content = "进入设置代码生成参数第二步页面")
	@Token(validateToken = false)
	@RequestMapping(value = "showSecondStepSettingPageView" , method = RequestMethod.POST)
	public ModelAndView showSecondStepSettingPage() {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("showSecondStepSettingPageView"));
		try {
			String author = getParameter("author");// 开发者姓名
			String jdbcDriver = getParameter("jdbcDriver");// 数据库连接驱动
			String jdbcUrl = getParameter("jdbcUrl");// 数据库链接地址
			String jdbcUserName = getParameter("jdbcUserName");// 数据库连接用户名
			String jdbcPassword = getParameter("jdbcPassword");// 是不健康连接密码
			String projectDir = getParameter("projectDir");// 工程所在目录
			String templatesMapping = getParameter("templatesMapping");// 模板映射
			String module = getParameter("module");// 模块
			String templateDir = getParameter("templateDir");// 模板所在目录
			String javaFileOutDir = getParameter("javaFileOutDir");// 生成的java文件保存目录
			String viewFileOutDir = getParameter("viewFileOutDir");// 生成的视图文件保存目录
			GenerateConfig customGenerateBaseConfig = new GenerateConfig(projectDir , templatesMapping , module , templateDir , javaFileOutDir , viewFileOutDir , jdbcDriver , jdbcUrl , jdbcUserName , jdbcPassword , author);
			HttpSession session = request.getSession();
			session.setAttribute("generateCustomConfig" , customGenerateBaseConfig);
			List<String> allCatalog = this.codeGenerateService.getAllCatalog();
			mav.addObject("customGenerateBaseConfig" , customGenerateBaseConfig);
			mav.addObject("allCatalog" , allCatalog);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	@RequestLog(content = "进入设置代码生成参数第三步页面")
	@Token(validateToken = false)
	@RequestMapping(value = "showThirdStepSettingPage" , method = RequestMethod.POST)
	@SuppressWarnings("unchecked")
	public ModelAndView showThirdStepSettingPage() {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("showThirdStepSettingPageView"));
		try {
			String catalog = getParameter("catalog");
			String tableName = getParameter("tableName");
			List<TableColumnBean> columns = this.codeGenerateService.getTableColumns(catalog , tableName);
			// 删除无用的列映射记录
			this.sysTableColumnMappingService.deleteNotGenerateColumnMapping();
			// 外键信息
			List<ForeignKeyBean> refTables = new ArrayList<ForeignKeyBean>();
			// 新增列列映射记录
			List<String> alreadyLoadTableMappings = new ArrayList<String>();
			// 所有列分类容器(每一个表的列，新装入一个小容器，再放入一个大容器)
			List<List<SysTableColumnMapping>> tableColumnMappings = new ArrayList<List<SysTableColumnMapping>>();
			// 选中表及关联表映射容器
			List<SysTableColumnMapping> allColumnMappings = new ArrayList<SysTableColumnMapping>();
			// 选中表及关联表的默认参数容器
			Map<String , String> defaultConfigs = new HashMap<String , String>();
			// 加载关联表数据库列及关联表外键
			loadRererenceTable(catalog , columns , refTables , allColumnMappings , alreadyLoadTableMappings , defaultConfigs , tableColumnMappings);
			// 颠倒通过递归将小容器放入大容器的顺序
			Collections.reverse(tableColumnMappings);
			// 批量保存列映射信息
			this.sysTableColumnMappingService.hibernateBatchSave(allColumnMappings);
			String templatesMappings = null;
			Object customGenerateBaseConfigObj = getSession().getAttribute("generateCustomConfig");
			if(customGenerateBaseConfigObj instanceof GenerateConfig) {
				GenerateConfig gc = (GenerateConfig)customGenerateBaseConfigObj;
				gc.setForeignKeys(refTables);
				templatesMappings = gc.getTemplatesMapping();
			}
			// 将相关表的业务描述默认值设置为数据库表的备注
			TempTable tt = null;
			SysTableColumnMapping sysTableColumnMapping = null;
			List<TempTable> tables = new ArrayList<TempTable>();
			for(List<SysTableColumnMapping> tableColumns : tableColumnMappings) {
				if(tableColumns != null && !tableColumns.isEmpty()) {
					sysTableColumnMapping = tableColumns.get(0);
					String scheme = sysTableColumnMapping.getScheme();
					String _tableName = sysTableColumnMapping.getTableName();
					String remark = null;
					HttpSession session = this.getSession();
					Object allTablesCacheObj = session.getAttribute("allTablesCache");
					if(allTablesCacheObj != null) {
						if(allTablesCacheObj instanceof Map) {
							Map<String , List<TableBean>> allTablesCache = (Map<String , List<TableBean>>)allTablesCacheObj;
							List<TableBean> list = allTablesCache.get(catalog);
							for(TableBean tableBean : list) {
								if(tableBean.getName().equals(_tableName)) {
									remark = tableBean.getRemarks();
									break;
								}
							}
						}
					} else {
						remark = this.codeGenerateService.getTableRemarks(scheme , _tableName);
					}
					tt = new TempTable(remark , tableColumns);
					tables.add(tt);
					for(ForeignKeyBean foreignKeyBean : refTables) {
						if(foreignKeyBean.getReferenceTableName().equals(_tableName)) {
							foreignKeyBean.setReferenceTableRemarks(remark);
						}
					}
					if(_tableName.equals(tableName)) {
						mav.addObject("businessDescription" , remark);
					}
				}
			}
			mav.addObject("tables" , tables);
			mav.addObject("refTables" , refTables);
			mav.addObject("catalog" , catalog);
			mav.addObject("tableName" , tableName);
			mav.addObject("entityName" , StringUtils.converToJavaVariable(tableName , false));
			mav.addObject("templates" , templatesMappings);
			mav.addObject("defaultConfigs" , defaultConfigs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mav;
	}
	
	@ResponseBody
	@RequestLog(content = "生成工程代码")
	@Token(validateToken = false)
	@RequestMapping(value = "generateCode" , method = RequestMethod.POST)
	public String generateCode(@RequestParam(required = true) String entityName , @RequestParam(required = true) String tableName , @RequestParam(required = true) String catalog) {
		AjaxJsonResponse ajr = new AjaxJsonResponse("生成成功!");
		try {
			Object customGenerateBaseConfigObj = getSession().getAttribute("generateCustomConfig");
			if(customGenerateBaseConfigObj instanceof GenerateConfig) {
				Map<String , String> attrJsonConfigStrs = new HashMap<String , String>();
				Map<String , String> businessDescriptionMaps = new HashMap<String , String>();
				Map<String , String> logicDeleteMaps = new HashMap<String , String>();
				Map<String , Map<String , Boolean>> genFielsMaps = new HashMap<String , Map<String , Boolean>>();
				GenerateConfig gc = (GenerateConfig)customGenerateBaseConfigObj;
				Map<String , String []> parameterMap = getParameterMap(request);
				Set<String> keySet = parameterMap.keySet();
				for(String key : keySet) {
					if(StringUtils.endsWith(key , "_attrJsonConfig")) {
						// 获取数据库表列的配置的属性
						String table_name = StringUtils.substringBeforeLast(key , "_attrJsonConfig");
						String table_attrJsonConfig = getParameter(key);
						attrJsonConfigStrs.put(table_name , table_attrJsonConfig);
						// 获取生成文件选项
						String templatesMappings = gc.getTemplatesMapping();
						Map<String , Boolean> genfiel = new HashMap<String , Boolean>();
						for(String tmm : templatesMappings.split(",")) {
							tmm = StringEscapeUtils.unescapeHtml(tmm);
							String [] tm = tmm.split("->");
							String tempSuffix = tm[0];
							String temPackages = tm[1];
							String isGenFile = getParameter(table_name + "_" + temPackages.replace("." , "-"));
							genfiel.put(tempSuffix , BooleanUtils.toBooleanObject(isGenFile));
						}
						genFielsMaps.put(table_name , genfiel);
						// 获取业务描述
						String businessDescription = getParameter(table_name + "_businessDescription");
						businessDescriptionMaps.put(table_name , businessDescription);
						String isLogicDelete = getParameter(table_name + "_isLogicDelete");
						if(BooleanUtils.toBoolean(isLogicDelete)) {
							String deleteIdentifyingField = getParameter(table_name + "_deleteIdentifyingField");
							logicDeleteMaps.put(table_name , deleteIdentifyingField);
						}
					}
				}
				gc.setCatalog(catalog);
				gc.setAttrJsonConfigStrs(attrJsonConfigStrs);
				gc.setGenFielsMaps(genFielsMaps);
				gc.setLogicDeleteMaps(logicDeleteMaps);
				gc.setBusinessDescriptionMaps(businessDescriptionMaps);
				this.codeGenerateService.autoGenCode(gc);
			} else {
				ajr.setResCode(-1);
				ajr.setResMsg("生成失败!");
			}
		} catch (Exception e) {
			ajr.setResMsg(e.getMessage());
			ajr.setResCode(500);
			e.printStackTrace();
		}
		return ajr.jsonResponse(false);
	}
	
	@ResponseBody
	@RequestLog(content = "获取数据源数据的json串")
	@RequestMapping(value = "getDataSourcesData" , method = RequestMethod.GET)
	public String getDataSourcesData(HttpServletResponse response) throws IOException {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		Connection connection = null;
		PreparedStatement prepareStatement = null;
		ResultSet resultSet = null;
		try {
			String sql = getParameter("sql");
			Object customGenerateBaseConfigObj = getSession().getAttribute("generateCustomConfig");
			if(customGenerateBaseConfigObj instanceof GenerateConfig) {
				GenerateConfig gc = (GenerateConfig)customGenerateBaseConfigObj;
				String jdbcDriver = gc.getJdbcDriver();
				String jdbcUrl = gc.getJdbcUrl();
				String jdbcUserName = gc.getJdbcUserName();
				String jdbcPassword = gc.getJdbcPassword();
				Class.forName(jdbcDriver);
				connection = DriverManager.getConnection(jdbcUrl , jdbcUserName , jdbcPassword);
				prepareStatement = connection.prepareStatement(StringEscapeUtils.escapeSql(sql));
				resultSet = prepareStatement.executeQuery();
				List<Map<String , Object>> dataList = new ArrayList<Map<String , Object>>();
				while (resultSet.next()) {
					Map<String , Object> data = new TreeMap<String , Object>();
					data.put("keyColumn" , StringEscapeUtils.escapeHtml(resultSet.getString("keyColumn")));
					data.put("valueColumn" , StringEscapeUtils.escapeHtml(resultSet.getString("valueColumn")));
					dataList.add(data);
				}
				ajr.setData(dataList);
			}
		} catch (ClassNotFoundException e) {
			ajr.setResMsg("无法加载指定的驱动,数据库连接失败!");
			ajr.setResCode(500);
			e.printStackTrace();
		} catch (Exception e) {
			ajr.setResMsg("数据库连接失败(" + e.getMessage() + ")!");
			ajr.setResCode(500);
			e.printStackTrace();
		} finally {
			if(resultSet != null) {
				try {
					resultSet.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(prepareStatement != null) {
				try {
					prepareStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return ajr.jsonResponse(true);
	}
	
	@ResponseBody
	@RequestLog(content = "获取表的所有列的json串")
	@RequestMapping(value = "tableColumnsJsonStr" , method = RequestMethod.GET)
	public String tableColumnsJsonStr(HttpServletResponse response) throws IOException {
		AjaxJsonResponse ajr = new AjaxJsonResponse("获取成功!");
		try {
			String catalog = getParameter("catalog");
			String tableName = getParameter("tableName");
			List<TableColumnBean> columns = this.codeGenerateService.getTableColumns(catalog , tableName);
			ajr.setData(columns);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	
	@RequestLog(content = "获取表的所有列")
	@RequestMapping(value = "tableColumns" , method = RequestMethod.GET)
	public ModelAndView tableColumns(HttpServletResponse response) throws IOException {
		ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tableColumnsView"));
		try {
			String catalog = getParameter("catalog");
			String tableName = getParameter("tableName");
			List<TableColumnBean> columns = this.codeGenerateService.getTableColumns(catalog , tableName);
			mav.addObject("columns" , columns);
			mav.addObject("tableName" , tableName);
		} catch (Exception e) {
			mav.addObject("exception" , e.getMessage());
			e.printStackTrace(response.getWriter());
			e.printStackTrace();
		}
		return mav;
	}
	
	@ResponseBody
	@RequestLog(content = "测试数据库是否可以连接成功")
	@RequestMapping(value = "testConnection" , method = RequestMethod.GET)
	public String testConnection() {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		Connection connection = null;
		try {
			String jdbcDriver = getParameter("jdbcDriver");
			String jdbcUrl = getParameter("jdbcUrl");
			String jdbcUserName = getParameter("jdbcUserName");
			String jdbcPassword = getParameter("jdbcPassword");
			Class.forName(jdbcDriver);
			connection = DriverManager.getConnection(jdbcUrl , jdbcUserName , jdbcPassword);
			if(connection != null) {
				if(!connection.isReadOnly()) {
					ajr.setData("数据库连接成功!");
				} else {
					ajr.setData("数据库连接成功,但是没有写入权限!");
				}
			} else {
				ajr.setData("数据库连接失败!");
			}
		} catch (ClassNotFoundException e) {
			ajr.setResMsg("无法加载指定的驱动,数据库连接失败!");
			ajr.setResCode(500);
			e.printStackTrace();
		} catch (Exception e) {
			ajr.setResMsg("数据库连接失败(" + e.getMessage() + ")!");
			ajr.setResCode(500);
			e.printStackTrace();
		} finally {
			if(connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return ajr.jsonResponse(true);
	}
	
	@ResponseBody
	@RequestLog(content = "获取数据库所有数据表json串")
	@RequestMapping(value = "getAllTable" , method = RequestMethod.GET)
	@SuppressWarnings("unchecked")
	public String getAllTable() {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			StringBuffer data = new StringBuffer();
			data.append("[");
			String catalog = getParameter("catalog");
			if(StringUtils.isBlank(catalog)) {// 所有方案列表
				List<String> allCatalog = this.codeGenerateService.getAllCatalog();
				allCatalog.parallelStream().sorted((o1 , o2) -> {
					return o1.compareTo(o2);
				}).forEachOrdered((cata) -> {
					data.append("{ name: \"" + cata + "\", type: \"" + "folder" + "\", params: {catalog:\"" + cata + "\"}");
					data.append(",data: [");
					data.append("]},");
				});
			} else {// 数据表列表
				List<TableBean> allTable = this.codeGenerateService.getAllTable(catalog);
				HttpSession session = this.getSession();
				Object allTablesCacheObj = session.getAttribute("allTablesCache");
				if(allTablesCacheObj == null) {
					allTablesCacheObj = new HashMap<String , List<TableBean>>();
				}
				if(allTablesCacheObj instanceof Map) {
					Map<String , List<TableBean>> allTablesCache = (Map<String , List<TableBean>>)allTablesCacheObj;
					allTablesCache.remove(catalog);
					allTablesCache.put(catalog , allTable);
				}
				allTable.parallelStream().sorted((o1 , o2) -> {
					return o1.getName().compareTo(o2.getName());
				}).forEachOrdered((table) -> {
					try {
						data.append("{ name: \"" + table.getName() + "\", type: \"" + "item" + "\", params:" + JSONUtil.toJsonStr(table));
						data.append(",data: [");
						data.append("]},");
					} catch (Exception e) {
						e.printStackTrace();
					}
				});
			}
			if(data.length() > 1) {
				data.deleteCharAt(data.length() - 1);
			}
			data.append("]");
			ajr.setData(data);
		} catch (Exception e) {
			ajr.setResMsg(e.getMessage());
			ajr.setResCode(500);
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	
	@ResponseBody
	@RequestLog(content = "获取服务器磁盘目录树json串")
	@RequestMapping(value = "redDiscJsonStr" , method = RequestMethod.GET)
	public String redDiscJsonStr() {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			String dir = getParameter("dir");
			String isIncludeFile = getParameter("isIncludeFile");
			String childrenFileToJsonStr = FileUtils.readChildrenFileToJsonStr(dir , BooleanUtils.toBoolean(isIncludeFile));
			ajr.setData(childrenFileToJsonStr);
		} catch (JsonProcessingException e) {
			ajr.setResMsg(e.getMessage());
			ajr.setResCode(500);
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	
	@ResponseBody
	@RequestLog(content = "获取工程目录树json串")
	@RequestMapping(value = "redProjectJsonStr" , method = RequestMethod.GET)
	public String redProjectJsonStr() {
		AjaxJsonResponse ajr = new AjaxJsonResponse();
		try {
			String projectDir = getParameter("projectDir");
			if(StringUtils.isNotBlank(projectDir)) {
				String data = FileUtils.readFileToJsonStr(projectDir , true);
				ajr.setData(data.toString());
			} else {
				ajr.setData("[]");
			}
		} catch (JsonProcessingException e) {
			ajr.setResMsg(e.getMessage());
			ajr.setResCode(500);
			e.printStackTrace();
		}
		return ajr.jsonResponse(true);
	}
	
	/**
	 * 查找某一表的引用表
	 * 
	 * @param catalog
	 *            数据库名
	 * @param columns
	 *            所有列
	 * @param refTables
	 *            引用表集合
	 * @param allColumnMappings
	 *            所有列映射容器
	 * 
	 * @param alreadyLoadTableMappings
	 *            已经加载过的关联表表名容器
	 * @param defaultConfigs
	 *            列映射
	 * @param tableColumnMappings
	 *            所有列分类映射容器
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 * @throws InvocationTargetException
	 * @throws JsonProcessingException
	 */
	private void loadRererenceTable(String catalog , List<TableColumnBean> columns , List<ForeignKeyBean> refTables , List<SysTableColumnMapping> allColumnMappings , List<String> alreadyLoadTableMappings , Map<String , String> defaultConfigs , List<List<SysTableColumnMapping>> tableColumnMappings) throws ClassNotFoundException , InstantiationException , IllegalAccessException , SQLException , InvocationTargetException , JsonProcessingException {
		List<SysTableColumnMapping> tableColumnMapping = new ArrayList<SysTableColumnMapping>();
		if(columns != null && !columns.isEmpty() && alreadyLoadTableMappings.contains(columns.get(0).getTableName())) {
			return;
		}
		for(TableColumnBean tableColumnBean : columns) {
			SysTableColumnMapping stcm = new SysTableColumnMapping();
			BeanUtils.copyProperties(stcm , tableColumnBean);
			if(tableColumnBean.getIsForeignKey() != null && tableColumnBean.getIsForeignKey()) {
				ForeignKeyBean fkb = new ForeignKeyBean(tableColumnBean.getForeignKeyName() , tableColumnBean.getReferenceTable() , tableColumnBean.getColumnName() , tableColumnBean.getReferenceColumn() , tableColumnBean.getRemarks());
				boolean isHave = false;
				for(ForeignKeyBean _fkb : refTables) {
					if(_fkb.getReferenceTableName().equals(fkb.getReferenceTableName())) {
						isHave = true;
					}
				}
				if(!isHave) {// 若从未加载这加载此外键相关表
					refTables.add(fkb);
				}
				String referenceTableName = fkb.getReferenceTableName();
				List<TableColumnBean> referenceTableColumns = this.codeGenerateService.getTableColumns(catalog , referenceTableName);
				// 数据源字段设置
				stcm.setDatasourceCatalog(catalog);
				stcm.setDatasourceTableName(referenceTableName);
				Optional<TableColumnBean> findFirst = referenceTableColumns.parallelStream().filter(new Predicate<TableColumnBean>() {
					
					@Override
					public boolean test(TableColumnBean t) {
						return t.getIsPrimaryKey();
					}
					
				}).findFirst();
				if(findFirst.isPresent()) {
					stcm.setDatasourceKeyColumn(findFirst.get().getColumnName());
				}
				// 递归加载关联表
				if(!referenceTableName.equals(tableColumnBean.getTableName())) {// 自关联外键，不进行递归
					loadRererenceTable(catalog , referenceTableColumns , refTables , allColumnMappings , alreadyLoadTableMappings , defaultConfigs , tableColumnMappings);
				}
			}
			// 主键列默认不作为搜搜条件
			stcm.setIsSearchable(!stcm.getIsPrimaryKey());
			// 特殊字段处理
			stcm.setScheme(catalog);
			stcm.setColumnPrecision(tableColumnBean.getPrecision());
			stcm.setColumnScale(tableColumnBean.getScale());
			stcm.setStatus(0);
			String lowerCaseFieldName = stcm.getColumnJavaFieldName().toLowerCase();
			boolean isVersion = StringUtils.contains(lowerCaseFieldName , "version");
			boolean isNowLoginUserIdentifying = StringUtils.contains(lowerCaseFieldName , "createuser");
			boolean isCreateTime = StringUtils.contains(lowerCaseFieldName , "createtime") || //
			StringUtils.contains(lowerCaseFieldName , "create_time") || //
			StringUtils.contains(lowerCaseFieldName , "createdate") || //
			StringUtils.contains(lowerCaseFieldName , "create_date") || //
			StringUtils.contains(lowerCaseFieldName , "init_time") || //
			StringUtils.contains(lowerCaseFieldName , "init_date");
			boolean isModifiedTime = StringUtils.contains(lowerCaseFieldName , "updatetime") || //
			StringUtils.contains(lowerCaseFieldName , "update_time") || //
			StringUtils.contains(lowerCaseFieldName , "updatedate") || //
			StringUtils.contains(lowerCaseFieldName , "update_date") || //
			StringUtils.contains(lowerCaseFieldName , "modifiedtime") || //
			StringUtils.contains(lowerCaseFieldName , "modified_time") || //
			StringUtils.contains(lowerCaseFieldName , "modifieddate") || //
			StringUtils.contains(lowerCaseFieldName , "modified_date") || //
			StringUtils.contains(lowerCaseFieldName , "lastupdatetime") || //
			StringUtils.contains(lowerCaseFieldName , "last_update_time") || //
			StringUtils.contains(lowerCaseFieldName , "lastupdatedate") || //
			StringUtils.contains(lowerCaseFieldName , "last_update_date") || //
			StringUtils.contains(lowerCaseFieldName , "lastmodifiedtime") || //
			StringUtils.contains(lowerCaseFieldName , "last_modified_time") || //
			StringUtils.contains(lowerCaseFieldName , "lastmodifieddate") || //
			StringUtils.contains(lowerCaseFieldName , "last_modified_date");
			stcm.setIsCreateTime(isCreateTime);
			stcm.setIsModifiedTime(isModifiedTime);
			stcm.setIsAddCanEdit(!isCreateTime ? !isModifiedTime : false);
			stcm.setIsUpdateCanEdit(!isCreateTime ? !isModifiedTime : false);
			stcm.setIsVersionIdentifying(isVersion);
			stcm.setIsNowLoginUserIdentifying(isNowLoginUserIdentifying);
			// 版本标识列不可新增,不可编辑
			if((isVersion || isNowLoginUserIdentifying) && stcm.getIsAddCanEdit()) {
				stcm.setIsAddCanEdit(false);
			}
			if((isVersion || isNowLoginUserIdentifying) && stcm.getIsUpdateCanEdit()) {
				stcm.setIsUpdateCanEdit(false);
			}
			tableColumnMapping.add(stcm);
		}
		if(!tableColumnMapping.isEmpty()) {
			String tableName = tableColumnMapping.get(0).getTableName();
			alreadyLoadTableMappings.add(tableName);
			tableColumnMappings.add(tableColumnMapping);
			allColumnMappings.addAll(tableColumnMapping);
			String defaultConfig = genDefaultColumnAttr(allColumnMappings);
			if(!tableColumnMapping.isEmpty()) {
				defaultConfigs.put(tableName , defaultConfig);
			}
		}
	}
	
	/**
	 * 给数据库列生成默认属性
	 * 
	 * @param list
	 *            列集合
	 * @return
	 * @throws JsonProcessingException
	 */
	private String genDefaultColumnAttr(List<SysTableColumnMapping> list) throws JsonProcessingException {
		Map<String , CommonFormAttr> result = new HashMap<String , CommonFormAttr>();
		for(SysTableColumnMapping column : list) {
			String columnJavaType = column.getColumnJavaType();
			String columnJavaFieldName = column.getColumnJavaFieldName();
			String remarks = column.getRemarks();
			CommonFormAttr cfa = new CommonFormAttr();
			cfa.setId(columnJavaFieldName);
			cfa.setName(columnJavaFieldName);
			cfa.setTitle(remarks);
			cfa.setAlt(remarks);
			cfa.setPlaceholder(remarks);
			cfa.setSize(column.getColumnDisplaySize() + "");
			cfa.setType("text");
			cfa.addClass("form-control");
			cfa.addCustomerAttr("data-bv-message" , "The field is not valid");
			if(!column.getIsNullable()) {
				cfa.addCustomerAttr("data-bv-notempty" , "true");
				cfa.addCustomerAttr("data-bv-notempty-message" , "The field is required and cannot be empty");
			}
			switch(columnJavaType){
				case "java.lang.Byte":
					
					break;
				case "java.lang.Boolean":
					cfa.setName("");
					cfa.setType("checkbox");
					cfa.addClass("checkbox-slider");
					cfa.addClass("slider-icon");
					cfa.addClass("yesno");
					cfa.addCustomerAttr("data-target-input-name" , columnJavaFieldName);
					break;
				case "java.lang.Double":
					cfa.addCustomerAttr("data-bv-numeric" , "true");
					cfa.addCustomerAttr("data-bv-numeric-message" , "The field is numeric");
					break;
				case "java.lang.Short":
				case "java.lang.Integer":
				case "java.lang.Long":
				case "java.math.BigInteger":
					cfa.addCustomerAttr("data-bv-integer" , "true");
					cfa.addCustomerAttr(" data-bv-integer-message" , "The field is number");
					break;
				case "java.util.Date":
				case "java.sql.Time":
				case "java.sql.Timestamp":
					cfa.addClass("form-control");
					cfa.addClass("date-picker");
					cfa.addCustomerAttr("data-bv-date" , "true");
					cfa.addCustomerAttr("data-bv-date-message" , "请正确输入一个时间");
					cfa.addCustomerAttr("data-bv-date-format" , "YYYY-MM-DD hh:mm:ss");
					cfa.addEvent("onfocus" , "WdatePicker({doubleCalendar:true,dateFmt:'yyyy-MM-dd HH:mm:ss'})");
					break;
				case "java.lang.String":
					break;
				case "java.sql.Struct":
				case "java.sql.Array":
				case "java.sql.SQLXML":
				case "java.sql.Ref":
				case "byte[]":
			}
			column.setAttrsJsonStr(JSONUtil.toJsonStr(cfa));
			result.put(columnJavaFieldName , cfa);
		}
		return JSONUtil.toJsonStr(result);
	}
	
	public static class TempTable {
		
		private String remark;
		private List<SysTableColumnMapping> columns;
		
		public TempTable (){
			super();
		}
		
		public TempTable (String remark , List<SysTableColumnMapping> columns ){
			super();
			this.remark = remark;
			this.columns = columns;
		}
		
		public String getRemark() {
			return remark;
		}
		
		public void setRemark(String remark) {
			this.remark = remark;
		}
		
		public List<SysTableColumnMapping> getColumns() {
			return columns;
		}
		
		public void setColumns(List<SysTableColumnMapping> columns) {
			this.columns = columns;
		}
		
	}
}
